package jbase.project.system.core.support;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.script.ScriptEngine;
import javax.script.ScriptEngineFactory;
import javax.script.ScriptEngineManager;

public class LocalService {

	public static double[] fromDoubles(Double[] d) {
		int size = d.length;
		double[] ds = new double[size];
		for (int i = 0; i < size; i++) {
			ds[i] = d[i].doubleValue();
		}
		return ds;
	}

	public static final String search(String src, String pattern) {
		Pattern p = Pattern.compile(pattern);
		Matcher m = p.matcher(src);
		while (m.find()) {
			return m.group();
		}
		return null;
	}

	public static final String makeFinalText(String src) {
		String target = src;
		target = target.replaceAll("\\$\\{\\s*[tT][iI][mM][eE][sS][Tt][aA][mM][pP]\\s*\\}", makeTimestamp());
		target = target.replaceAll("\\$\\{\\s*[uU][uU][Ii][Dd]\\s*\\}", uuid());
		return target;
	}

	public static final String uuid() {
		return UUID.randomUUID().toString().replace("-", "").toUpperCase();
	}

	public static final String makeTimestamp() {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss");
		String timestamp = sdf.format(new Date());
		return timestamp.replace("-", "");
	}

	public static void listScriptEngines() {

		ScriptEngineManager sem = new ScriptEngineManager();
		List<ScriptEngineFactory> fs = sem.getEngineFactories();
		for (ScriptEngineFactory f : fs) {
		}
	}

	public static String listClassInfo(Class<?> clazz) {
		StringBuffer s = new StringBuffer();
		s.append("class:" + clazz.getName());
		return s.toString();
	}

	public static ScriptEngine createJavaScriptEngine() throws Exception {
		ScriptEngineManager scriptEngineManager = new ScriptEngineManager();
		ScriptEngine script = null;
		script = scriptEngineManager.getEngineByMimeType("text/javascript");
		if (script != null) {
			return script;
		} else {
			throw new Exception("Can not create JavaScript engine!");
		}
	}

	public static ScriptEngine createScalaEngine() throws Exception {
		ScriptEngineManager scriptEngineManager = new ScriptEngineManager();
		ScriptEngine script = null;
		script = scriptEngineManager.getEngineByExtension("scala");
		if (script != null) {
			return script;
		} else {
			script = scriptEngineManager.getEngineByMimeType("application/x-scala");
			if (script != null) {
				return script;
			} else {
				throw new Exception("Can not create Scala engine!");
			}
		}
	}

}
